#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
择偶条件管理API - 重构版，支持多选条件、智能推荐和匹配度计算
"""

from flask import request, current_app
from flask_restx import Resource, Namespace, fields
from app.services.mate_criteria_service import MateCriteriaService
from app.utils.auth import user_token_required
from app.utils.response import success_response, error_response
from app.utils.validators import validate_required_fields
from . import api

# 创建命名空间
mate_criteria_ns = Namespace('mate-criteria', description='择偶条件管理 - 重构版')

# 定义请求模型
mate_criteria_model = mate_criteria_ns.model('MateCriteria', {
    # 基础条件
    'min_age': fields.Integer(description='最小年龄'),
    'max_age': fields.Integer(description='最大年龄'),
    'min_height': fields.Integer(description='最小身高cm'),
    'max_height': fields.Integer(description='最大身高cm'),
    
    # 多选偏好条件
    'education_preferences': fields.List(fields.String, description='学历偏好'),
    'income_preferences': fields.List(fields.String, description='收入偏好'),
    'occupation_preferences': fields.List(fields.String, description='职业偏好'),
    'marital_preferences': fields.List(fields.String, description='婚姻状况偏好'),
    'housing_preferences': fields.List(fields.String, description='住房偏好'),
    'car_preferences': fields.List(fields.String, description='购车偏好'),
    'smoking_preferences': fields.List(fields.String, description='吸烟偏好'),
    'drinking_preferences': fields.List(fields.String, description='饮酒偏好'),
    'personality_preferences': fields.List(fields.String, description='性格偏好'),
    
    # 地区偏好
    'city_preferences': fields.List(fields.String, description='城市偏好'),
    
    # 其他条件
    'has_children_preference': fields.Integer(description='对方是否有孩子：-1不限0无1有'),
    'wants_children_preference': fields.Integer(description='对方是否要孩子：-1不限0不要1要'),
    'other_requirements': fields.String(description='其他要求')
})

match_score_model = mate_criteria_ns.model('MatchScore', {
    'target_user_id': fields.Integer(required=True, description='目标用户ID')
})

find_matches_model = mate_criteria_ns.model('FindMatches', {
    'page': fields.Integer(description='页码', default=1),
    'per_page': fields.Integer(description='每页数量', default=20)
})


@mate_criteria_ns.route('/mate-criteria')
class MateCriteriaAPI(Resource):
    """择偶条件管理接口"""
    
    @mate_criteria_ns.doc('get_mate_criteria')
    @user_token_required
    def get(self, current_user):
        """获取择偶条件"""
        try:
            criteria = MateCriteriaService.get_mate_criteria(current_user.id)
            if criteria:
                return success_response(criteria, '获取成功')
            else:
                return success_response(None, '暂未设置择偶条件')
        except Exception as e:
            current_app.logger.error(f"获取择偶条件异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)
    
    @mate_criteria_ns.expect(mate_criteria_model)
    @mate_criteria_ns.doc('update_mate_criteria')
    @user_token_required
    def put(self, current_user):
        """更新择偶条件（支持验证）"""
        try:
            data = request.get_json() or {}
            
            # 更新择偶条件（带验证）
            result = MateCriteriaService.update_mate_criteria(current_user.id, data)
            
            if not result['success']:
                errors = result.get('validation_errors', [])
                error_msg = result['error']
                if errors:
                    error_msg += f": {', '.join(errors)}"
                return error_response(error_msg, 400)
            
            return success_response(
                result['data'], 
                result['message']
            )
        except Exception as e:
            current_app.logger.error(f"更新择偶条件异常: {str(e)}")
            return error_response(f"更新失败: {str(e)}", 500)
    
    @mate_criteria_ns.doc('delete_mate_criteria')
    @user_token_required
    def delete(self, current_user):
        """删除择偶条件"""
        try:
            success = MateCriteriaService.delete_mate_criteria(current_user.id)
            if success:
                return success_response(message='择偶条件删除成功')
            else:
                return error_response('删除失败，择偶条件不存在', 400)
        except Exception as e:
            current_app.logger.error(f"删除择偶条件异常: {str(e)}")
            return error_response(f"删除失败: {str(e)}", 500)


@mate_criteria_ns.route('/mate-criteria/suggestions')
class MateCriteriaIntelligentSuggestionsAPI(Resource):
    """智能择偶条件建议接口"""
    
    @mate_criteria_ns.doc('get_intelligent_suggestions')
    @user_token_required
    def get(self, current_user):
        """获取智能择偶条件建议"""
        try:
            result = MateCriteriaService.get_intelligent_suggestions(current_user.id)
            
            if not result['success']:
                return error_response(result['error'], 400)
            
            return success_response(result['data'], '获取智能建议成功')
        except Exception as e:
            current_app.logger.error(f"获取智能建议异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)


@mate_criteria_ns.route('/mate-criteria/match-score')
class MatchScoreAPI(Resource):
    """匹配度计算接口"""
    
    @mate_criteria_ns.expect(match_score_model)
    @mate_criteria_ns.doc('calculate_match_score')
    @user_token_required
    def post(self, current_user):
        """计算与指定用户的匹配度"""
        try:
            # 验证必填字段
            is_valid, error_msg = validate_required_fields(['target_user_id'])
            if not is_valid:
                return error_response(error_msg, 400)
            
            data = request.get_json()
            target_user_id = data.get('target_user_id')
            
            if target_user_id == current_user.id:
                return error_response('不能计算与自己的匹配度', 400)
            
            # 计算匹配度
            match_result = MateCriteriaService.calculate_criteria_match_score(
                current_user.id, target_user_id
            )
            
            if 'error' in match_result:
                return error_response(match_result['error'], 400)
            
            return success_response(match_result, '匹配度计算完成')
        except Exception as e:
            current_app.logger.error(f"计算匹配度异常: {str(e)}")
            return error_response(f"计算失败: {str(e)}", 500)


@mate_criteria_ns.route('/mate-criteria/find-matches')
class FindMatchesAPI(Resource):
    """根据择偶条件查找匹配用户接口"""
    
    @mate_criteria_ns.doc('find_matches')
    @mate_criteria_ns.param('page', '页码', type='int', default=1)
    @mate_criteria_ns.param('per_page', '每页数量', type='int', default=20)
    @user_token_required
    def get(self, current_user):
        """根据择偶条件查找匹配用户"""
        try:
            page = int(request.args.get('page', 1))
            per_page = int(request.args.get('per_page', 20))
            
            if per_page > 50:  # 限制每页最大数量
                per_page = 50
            
            # 查找匹配用户
            result = MateCriteriaService.find_matches_by_criteria(
                current_user.id, page, per_page
            )
            
            if not result['success']:
                return error_response(result['error'], 400)
            
            return success_response(result['data'], '查找匹配用户成功')
        except Exception as e:
            current_app.logger.error(f"查找匹配用户异常: {str(e)}")
            return error_response(f"查找失败: {str(e)}", 500)


@mate_criteria_ns.route('/mate-criteria/validate')
class CriteriaValidationAPI(Resource):
    """择偶条件验证接口"""
    
    @mate_criteria_ns.expect(mate_criteria_model)
    @mate_criteria_ns.doc('validate_criteria')
    @user_token_required
    def post(self, current_user):
        """验证择偶条件数据"""
        try:
            data = request.get_json() or {}
            
            # 执行验证
            validation_result = MateCriteriaService._validate_criteria_data(data)
            
            return success_response(validation_result, '验证完成')
        except Exception as e:
            current_app.logger.error(f"验证择偶条件异常: {str(e)}")
            return error_response(f"验证失败: {str(e)}", 500)


# 兼容旧接口
@mate_criteria_ns.route('/mate-criteria/legacy/suggestions')
class LegacyCriteriaSuggestionsAPI(Resource):
    """旧版择偶条件建议接口（兼容）"""
    
    @mate_criteria_ns.doc('get_legacy_suggestions')
    @user_token_required
    def get(self, current_user):
        """获取择偶条件建议（兼容旧版）"""
        try:
            result = MateCriteriaService.get_intelligent_suggestions(current_user.id)
            
            if not result['success']:
                return error_response(result['error'], 400)
            
            # 转换为旧版格式
            suggestions = result['data']['basic_suggestions']
            return success_response(suggestions, '获取建议成功')
        except Exception as e:
            current_app.logger.error(f"获取择偶条件建议异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)


@mate_criteria_ns.route('/mate-criteria/legacy/match/<int:target_user_id>')
class LegacyMatchCheckAPI(Resource):
    """旧版匹配检查接口（兼容）"""
    
    @mate_criteria_ns.doc('legacy_match_check')
    @user_token_required
    def get(self, target_user_id, current_user):
        """检查与指定用户的匹配度（兼容旧版）"""
        try:
            match_result = MateCriteriaService.calculate_criteria_match_score(
                current_user.id, target_user_id
            )
            
            if 'error' in match_result:
                return error_response(match_result['error'], 400)
            
            # 转换为旧版格式
            is_match = match_result['score'] >= 60  # 60分以上算匹配
            return success_response({
                'is_match': is_match,
                'score': match_result['score'],
                'match_level': match_result['match_level'],
                'message': '匹配成功' if is_match else '不匹配'
            }, '检查完成')
        except Exception as e:
            current_app.logger.error(f"匹配检查异常: {str(e)}")
            return error_response(f"检查失败: {str(e)}", 500)


# 将命名空间注册到API实例
api.add_namespace(mate_criteria_ns) 